package com.bookpavilion.donate.interceptor;

import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JwtInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    private JwtUtil jwtUtil;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authHeader = request.getHeader("Authorization");
        if (authHeader!=null&&authHeader.startsWith("bpToken-")){
            String token = authHeader.substring(8);
            Claims claims = jwtUtil.parseJWT(token);
            if ("user".equals(claims.get("roles"))){
                request.setAttribute("user_claims",claims);
            }
        }
        return true;
    }
}
